package com.huhao.wshare.Profile;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Toast;

import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import java.io.IOException;
import static com.huhao.wshare.Config.LOGOUT_API;

import com.huhao.wshare.BaseActivity;
import com.huhao.wshare.LoginActivity;
import com.huhao.wshare.R;

public class SettingActivity extends BaseActivity {

    private RecyclerView recyclerViewSettings;
    private SettingAdapter settingAdapter;
    private List<SettingItem> settingItemList;
    private String token;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);

        // 初始化 Toolbar
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(false);
            getSupportActionBar().setDisplayShowTitleEnabled(false);
        }

        // 从 SharedPreferences 中获取 token
        SharedPreferences sp = getSharedPreferences("user_prefs", MODE_PRIVATE);
        token = sp.getString("token", null);

        // 初始化 RecyclerView
        recyclerViewSettings = findViewById(R.id.recyclerViewSettings);
        recyclerViewSettings.setLayoutManager(new LinearLayoutManager(this));

        // 初始化设置项数据
        settingItemList = new ArrayList<>();
        initSettingItems();

        // 设置适配器
        settingAdapter = new SettingAdapter(settingItemList, new SettingAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                switch (position) {
                    case 0:
                        // 点击更新用户信息
                        handleUpdateUserInfo();
                        break;
                    case 1:
                        // 点击重置密码
                        handleResetPassword();
                        break;
                    case 2:
                        // 点击退出登录，弹出确认框
                        showLogoutConfirmationDialog();
                        break;
                }
            }
        });
        recyclerViewSettings.setAdapter(settingAdapter);
    }

    private void initSettingItems() {
        // 添加新设置项
        settingItemList.add(new SettingItem("更新用户信息", "修改个人信息"));
        settingItemList.add(new SettingItem("重置密码", "修改登录密码"));
        settingItemList.add(new SettingItem("退出登录", "退出当前账号"));
    }

    private void handleUpdateUserInfo() {
        Intent intent = new Intent(SettingActivity.this, UpdateProfileActivity.class);
        startActivity(intent);
    }

    private void handleResetPassword() {
        Intent intent = new Intent(SettingActivity.this, ResetPasswordActivity.class);
        startActivity(intent);
    }

    private void showLogoutConfirmationDialog() {
        new AlertDialog.Builder(this)
                .setTitle("确认退出")
                .setMessage("确定要退出当前账号吗？")
                .setPositiveButton("确定", (dialog, which) -> {
                    doLogout();
                })
                .setNegativeButton("取消", (dialog, which) -> {
                    dialog.dismiss();
                })
                .show();
    }

    private void doLogout() {
        Request request = new Request.Builder()
                .url(LOGOUT_API)
                .post(RequestBody.create("", MediaType.get("application/x-www-form-urlencoded")))
                .addHeader("Authorization", "Bearer " + token)
                .build();

        // 发送网络请求
        new OkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> Toast.makeText(SettingActivity.this, "网络连接失败", Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    // 登出成功，清除 SharedPreferences
                    SharedPreferences sp = getSharedPreferences("user_prefs", MODE_PRIVATE);
                    sp.edit()
                            .clear()
                            .apply();
                    runOnUiThread(() -> {
                        Toast.makeText(SettingActivity.this, "登出成功", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(SettingActivity.this, LoginActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                        finish();
                    });
                } else {
                    runOnUiThread(() -> Toast.makeText(SettingActivity.this, "登出失败，请稍后重试", Toast.LENGTH_SHORT).show());
                }
            }
        });
    }

    // 设置项数据类
    public static class SettingItem {
        private String title;
        private String description;

        public SettingItem(String title, String description) {
            this.title = title;
            this.description = description;
        }

        public String getTitle() {
            return title;
        }

        public String getDescription() {
            return description;
        }
    }

    // 设置项适配器类
    public static class SettingAdapter extends RecyclerView.Adapter<SettingAdapter.SettingViewHolder> {

        private List<SettingItem> settingItemList;
        private OnItemClickListener onItemClickListener;

        public SettingAdapter(List<SettingItem> settingItemList, OnItemClickListener onItemClickListener) {
            this.settingItemList = settingItemList;
            this.onItemClickListener = onItemClickListener;
        }

        @Override
        public SettingViewHolder onCreateViewHolder(android.view.ViewGroup parent, int viewType) {
            android.view.View view = android.view.LayoutInflater.from(parent.getContext())
                    .inflate(android.R.layout.simple_list_item_2, parent, false);
            return new SettingViewHolder(view);
        }

        @Override
        public void onBindViewHolder(SettingViewHolder holder, int position) {
            SettingItem item = settingItemList.get(position);
            holder.text1.setText(item.getTitle());
            holder.text2.setText(item.getDescription());
            holder.itemView.setOnClickListener(v -> {
                if (onItemClickListener != null) {
                    onItemClickListener.onItemClick(position);
                }
            });
        }

        @Override
        public int getItemCount() {
            return settingItemList.size();
        }

        public static class SettingViewHolder extends RecyclerView.ViewHolder {
            android.widget.TextView text1;
            android.widget.TextView text2;

            public SettingViewHolder(android.view.View itemView) {
                super(itemView);
                text1 = itemView.findViewById(android.R.id.text1);
                text2 = itemView.findViewById(android.R.id.text2);
            }
        }

        public interface OnItemClickListener {
            void onItemClick(int position);
        }
    }

    // 重写 onSupportNavigateUp 方法处理返回按钮点击事件
    @Override
    public boolean onSupportNavigateUp() {
        finish();
        return true;
    }
}